package cn.com.lsy.product.lepao.util;

import com.alibaba.fastjson.JSON;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class WechatUserUtil {

    /**
     * 根据openid获取用户信息
     * @param openId
     * @param token
     * @return
     */
    /**
     * 获取微信用户
     * @param openid
     * @param accesstoken
     * @return
     */
    public static String getUserInfo(String openid,String accesstoken) {
        String token="";
        String url ="https://api.weixin.qq.com/sns/userinfo?access_token="+accesstoken+"&openid="+openid;
        try {
            URL urlGet = new URL(url);
            HttpURLConnection http = (HttpURLConnection) urlGet
                    .openConnection();
            http.setRequestMethod("GET"); // 必须是get方式请求
            http.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded");
            http.setDoOutput(true);
            http.setDoInput(true);
            System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
            System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
            http.connect();
            InputStream is = http.getInputStream();
            int size = is.available();
            byte[] jsonBytes = new byte[size];
            is.read(jsonBytes);
            token = new String(jsonBytes, "UTF-8");
            System.err.println(token);
            is.close();
            if(token.contains("nickname")){
                return token;
            }

            else{
                return null;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return token;
    }
}
